/**
 * 设置页面
 */

import Pubsub from '../../helper/Pubsub.js';
import State from '../../helper/State.js';
import SystemFonts from '../../helper/system-font-families.js';

const systemFonts = new SystemFonts();

class PageSetting {
  constructor($wrapper) {
    const _this = this;

    _this.$wrapper = $wrapper;
    _this.tpl =
`<div class="page">
  <div class="mdui-subheader">系统设置</div>
  <div class="mdui-card" style="overflow: visible">
    <div class="mdui-list">
      <!-- <div class="mdui-list-item hover-transparent">
        <div class="mdui-list-item-content">历史记录保存数量</div>
        <div class="mdui-textfield mdui-p-a-0">
          <input class="config-historyCount mdui-textfield-input" type="number" placeholder="数量" value="${State.getConfig('historyCount')}"/>
        </div>
      </div> -->
      <div class="mdui-list-item hover-transparent">
        <div class="mdui-list-item-content">系统英文字体</div>
        <select class="config-systemFontEN mdui-select"></select>
      </div>
      <div class="mdui-list-item hover-transparent">
        <div class="mdui-list-item-content">系统中文字体</div>
        <select class="config-systemFontZH mdui-select"></select>
      </div>
      <div class="mdui-list-item hover-transparent">
        <div class="mdui-list-item-content">文章目录深度</div>
        <select class="config-directoryMaxDepth mdui-select" mdui-select="{gutter: 64}">
          <option value="1" ${State.getConfig('directoryMaxDepth') === 1 ? 'selected' : ''}>H1</option>
          <option value="2" ${State.getConfig('directoryMaxDepth') === 2 ? 'selected' : ''}>H2</option>
          <option value="3" ${State.getConfig('directoryMaxDepth') === 3 ? 'selected' : ''}>H3</option>
          <option value="4" ${State.getConfig('directoryMaxDepth') === 4 ? 'selected' : ''}>H4</option>
          <option value="5" ${State.getConfig('directoryMaxDepth') === 5 ? 'selected' : ''}>H5</option>
          <option value="6" ${State.getConfig('directoryMaxDepth') === 6 ? 'selected' : ''}>H6</option>
        </select>
      </div>
    </div>
  </div>

  <div class="mdui-subheader">支持的文件扩展名，每行一个</div>
  <div class="mdui-card mdui-p-x-3">
    <div class="mdui-textfield mdui-p-t-1 mdui-p-b-2">
      <textarea class="config-markdownExtensions mdui-textfield-input" placeholder="在此输入支持的文件扩展名，每行一个">${State.getConfig('markdownExtensions').join("\r\n")}</textarea>
    </div>
  </div>

  <div class="mdui-subheader">Markdown 解析设置</div>
  <div class="mdui-card mdui-p-y-2 mdui-p-x-3">
    <div>
      <label class="mdui-checkbox">
        <input class="config-markdownToc" data-name="markdownToc" type="checkbox" ${State.getConfig('markdownToc') ? 'checked' : ''}/>
        <i class="mdui-checkbox-icon"></i>
        解析 [TOC]
      </label> 
    </div>
    <div>
      <label class="mdui-checkbox">
        <input class="config-markdownKatex" data-name="markdownKatex" type="checkbox" ${State.getConfig('markdownKatex') ? 'checked' : ''}/>
        <i class="mdui-checkbox-icon"></i>
        解析公式
      </label> 
    </div>
    <div>
      <label class="mdui-checkbox">
        <input class="config-markdownFlowchart" data-name="markdownFlowchart" type="checkbox" ${State.getConfig('markdownFlowchart') ? 'checked' : ''}/>
        <i class="mdui-checkbox-icon"></i>
        解析流程图
      </label> 
    </div>
    <div>
      <label class="mdui-checkbox">
        <input class="config-markdownSequenceDiagrams" data-name="markdownSequenceDiagrams" type="checkbox" ${State.getConfig('markdownSequenceDiagrams') ? 'checked' : ''}/>
        <i class="mdui-checkbox-icon"></i>
        解析时序图
      </label> 
    </div>
    <div>
      <label class="mdui-checkbox">
        <input class="config-markdownCodeLine" data-name="markdownCodeLine" type="checkbox" ${State.getConfig('markdownCodeLine') ? 'checked' : ''}/>
        <i class="mdui-checkbox-icon"></i>
        显示代码块行号
      </label> 
    </div>
  </div>
  
  <div class="mdui-subheader">自定义 CSS
    <button class="reset-all-custom-css mdui-btn mdui-btn-icon mdui-btn-dense mdui-color-theme-icon mdui-ripple" mdui-tooltip="{content: '恢复默认样式', position: 'bottom'}">
      <i class="mdui-icon material-icons">redo</i>
    </button>
  </div>
  <div class="mdui-panel" mdui-panel>
    <div class="mdui-panel-item">
      <div class="mdui-panel-item-header">
        <div class="mdui-panel-item-title">暗色主题下的 Markdown CSS</div>
        <i class="mdui-panel-item-arrow mdui-icon material-icons">keyboard_arrow_down</i>
      </div>
      <div class="custom-css mdui-panel-item-body">
        <div class="custom-css-editor" id="ace-markdown-css-editor"></div>
        <div class="mdui-panel-item-actions">
          <button class="mdui-btn mdui-ripple reset-custom-css" data-type="markdownCSS">重置</button>
          <button class="mdui-btn mdui-color-theme-accent mdui-ripple save-custom-css" data-type="markdownCSS">保存</button>
        </div>
      </div>
    </div>
    
    <div class="mdui-panel-item">
      <div class="mdui-panel-item-header">
        <div class="mdui-panel-item-title">亮色主题下的 Markdown CSS</div>
        <i class="mdui-panel-item-arrow mdui-icon material-icons">keyboard_arrow_down</i>
      </div>
      <div class="custom-css mdui-panel-item-body">
        <div class="custom-css-editor" id="ace-light-markdown-css-editor"></div>
        <div class="mdui-panel-item-actions">
          <div class="mdui-typo-caption-opacity mdui-typo mdui-float-left mdui-m-t-1">此处只编写与“暗色主题下的 Markdown CSS”不同部分的代码即可</div>
          <button class="mdui-btn mdui-ripple reset-custom-css" data-type="markdownLightCSS">重置</button>
          <button class="mdui-btn mdui-color-theme-accent mdui-ripple save-custom-css" data-type="markdownLightCSS">保存</button>
        </div>
      </div>
    </div>
    
    <div class="mdui-panel-item">
      <div class="mdui-panel-item-header">
        <div class="mdui-panel-item-title">暗色主题下的代码高亮 CSS</div>
        <i class="mdui-panel-item-arrow mdui-icon material-icons">keyboard_arrow_down</i>
      </div>
      <div class="custom-css mdui-panel-item-body">
        <div class="custom-css-editor" id="ace-dark-highlight-css-editor"></div>
        <div class="mdui-panel-item-actions">
          <div class="mdui-typo-caption-opacity mdui-typo mdui-float-left mdui-m-t-1"><a href="https://github.com/isagalaev/highlight.js/tree/master/src/styles">点击此处</a>查找更多代码高亮样式</div>
          <button class="mdui-btn mdui-ripple reset-custom-css" data-type="highlightDarkCSS">重置</button>
          <button class="mdui-btn mdui-color-theme-accent mdui-ripple save-custom-css" data-type="highlightDarkCSS">保存</button>
        </div>
      </div>
    </div>
    
    <div class="mdui-panel-item">
      <div class="mdui-panel-item-header">
        <div class="mdui-panel-item-title">亮色主题下的代码高亮 CSS</div>
        <i class="mdui-panel-item-arrow mdui-icon material-icons">keyboard_arrow_down</i>
      </div>
      <div class="custom-css mdui-panel-item-body">
        <div class="custom-css-editor" id="ace-light-highlight-css-editor"></div>
        <div class="mdui-panel-item-actions">
          <div class="mdui-typo-caption-opacity mdui-typo mdui-float-left mdui-m-t-1"><a href="https://github.com/isagalaev/highlight.js/tree/master/src/styles">点击此处</a>查找更多代码高亮样式</div>
          <button class="mdui-btn mdui-ripple reset-custom-css" data-type="highlightLightCSS">重置</button>
          <button class="mdui-btn mdui-color-theme-accent mdui-ripple save-custom-css" data-type="highlightLightCSS">保存</button>
        </div>
      </div>
    </div>
  </div>
  <button class="reset-all mdui-btn mdui-color-theme-accent mdui-ripple mdui-center mdui-m-t-5">重置所有设置</button>
</div>`;

    _this.$wrapper.html(_this.tpl).data('rendered', true);

    _this.editorInit();

    _this.$setting = {
      directoryMaxDepth: $$('#setting .config-directoryMaxDepth'),
      historyCount: $$('#setting .config-historyCount'),
      systemFontEN: $$('#setting .config-systemFontEN'),
      systemFontZH: $$('#setting .config-systemFontZH'),
      markdownExtensions: $$('#setting .config-markdownExtensions'),
      markdownToc: $$('#setting .config-markdownToc'),
      markdownKatex: $$('#setting .config-markdownKatex'),
      markdownFlowchart: $$('#setting .config-markdownFlowchart'),
      markdownSequenceDiagrams: $$('#setting .config-markdownSequenceDiagrams'),
      markdownCodeLine: $$('#setting .config-markdownCodeLine'),

      resetAll: $$('#setting .reset-all')
    };

    /**
     * 加载系统字体
     */
    systemFonts.getFonts().then(
      (fontList) => {

        const fontRegex = /^[a-zA_Z0-9\s]+$/i;

        fontList.forEach(function(font, i, fonts) {
          // 移除字体名的引号
          fonts[i] = font.replaceAll('"', '');

          // 过滤乱码的字体
          if (!fontRegex.test(fonts[i])) {
            delete fonts[i];
          }
        });

        let htmlEN = '<option value="">default font</option>';
        let htmlZH = '<option value="">默认字体</option>';

        fontList.forEach(function(font) {
          htmlEN += `<option value="${font}" ${State.getConfig('systemFontEN') === font ? 'selected' : ''}>${font}</option>`;
          htmlZH += `<option value="${font}" ${State.getConfig('systemFontZH') === font ? 'selected' : ''}>${font}</option>`;
        });

        _this.$setting.systemFontEN.html(htmlEN);
        _this.$setting.systemFontZH.html(htmlZH);
      }
    );

    /**
     * 切换字体
     */
    _this.$setting.systemFontEN.on('change', function(e) {
      State.setConfig('systemFontEN', e.target.value);
      Pubsub.emit('custom-css-changed');
    });

    _this.$setting.systemFontZH.on('change', function(e) {
      State.setConfig('systemFontZH', e.target.value);
      Pubsub.emit('custom-css-changed');
    });

    /**
     * 切换到设置页面
     */
    Pubsub.subscribe('page-setting-open', () => {
      // 更新多行输入框高度
      _this.$setting.markdownExtensions.trigger('blur');
    });

    /**
     * 更新历史记录数量
     */
    _this.$setting.historyCount.on('input', function() {
      State.setConfig('historyCount', $$(this).val());
    });

    /**
     * 更新文章目录解析深度
     */
    _this.$setting.directoryMaxDepth.on('change', function(e) {
      State.setConfig('directoryMaxDepth', parseInt($$(this).val()));
      Pubsub.emit('re-render-current-files');
    });

    /**
     * 文件扩展名更新
     */
    _this.$setting.markdownExtensions.on('blur', function() {
      let $this = $$(this);
      let input = $this.val();
      let value = input.split("\n").filter(function(n) {return n;});
      State.setConfig('markdownExtensions', value);
    });

    /**
     * 更新 Markdown TOC 解析设置
     */
    _this.$setting.markdownToc.on('change', function() {
      State.setConfig('markdownToc', $$(this).is(':checked'));
      Pubsub.emit('re-render-current-files');
    });

    /**
     * 更新 Markdown 公式解析设置
     */
    _this.$setting.markdownKatex.on('change', function() {
      State.setConfig('markdownKatex', $$(this).is(':checked'));
      Pubsub.emit('re-render-current-files');
    });

    /**
     * 更新 markdown 流程图解析设置
     */
    _this.$setting.markdownFlowchart.on('change', function() {
      State.setConfig('markdownFlowchart', $$(this).is(':checked'));
      Pubsub.emit('re-render-current-files');
    });

    /**
     * 更新 Markdown 时序图解析设置
     */
    _this.$setting.markdownSequenceDiagrams.on('change', function() {
      State.setConfig('markdownSequenceDiagrams', $$(this).is(':checked'));
      Pubsub.emit('re-render-current-files');
    });

    /**
     * 更新 Markdown 代码块行号解析设置
     */
    _this.$setting.markdownCodeLine.on('change', function() {
      State.setConfig('markdownCodeLine', $$(this).is(':checked'));
      Pubsub.emit('re-render-current-files');
    });

    /**
     * 重置所有设置
     */
    _this.$setting.resetAll.on('click', function() {
      mdui.confirm('该操作将重置所有用户的自定义设置', '确认要重置设置？', function() {
        State.clearConfig();

        _this.$setting.historyCount.val(State.getConfig('historyCount'));
        _this.$setting.markdownExtensions.val(State.getConfig('markdownExtensions').join("\r\n"));

        if (State.getConfig('markdownToc')) {
          _this.$setting.markdownToc.attr('checked', '');
        } else {
          _this.$setting.markdownToc.removeAttr('checked');
        }

        if (State.getConfig('markdownKatex')) {
          _this.$setting.markdownKatex.attr('checked', '');
        } else {
          _this.$setting.markdownKatex.removeAttr('checked');
        }

        if (State.getConfig('markdownFlowchart')) {
          _this.$setting.markdownFlowchart.attr('checked', '');
        } else {
          _this.$setting.markdownFlowchart.removeAttr('checked');
        }

        if (State.getConfig('markdownSequenceDiagrams')) {
          _this.$setting.markdownSequenceDiagrams.attr('checked', '');
        } else {
          _this.$setting.markdownSequenceDiagrams.removeAttr('checked');
        }

        if (State.getConfig('markdownCodeLine')) {
          _this.$setting.markdownCodeLine.attr('checked', '');
        } else {
          _this.$setting.markdownCodeLine.removeAttr('checked');
        }

        Pubsub.emit('re-render-current-files');

        _this.resetCustomCSS();

        mdui.snackbar({
          message: '已重置所有设置',
          position: 'left-bottom'
        });
      }, function(){}, {
        confirmText: '确认',
        cancelText: '取消',
        history: false
      });
    });
  }

  /**
   * 初始化编辑器
   */
  editorInit() {
    const _this = this;

    // 初始化 ace 编辑器
    _this.editors = {
      markdownCSS: ace.edit('ace-markdown-css-editor'),
      markdownLightCSS: ace.edit('ace-light-markdown-css-editor'),
      highlightDarkCSS: ace.edit('ace-dark-highlight-css-editor'),
      highlightLightCSS: ace.edit('ace-light-highlight-css-editor')
    };

    $$.each(_this.editors, (key, editor) => {
      editor.setTheme('ace/theme/idle_fingers');
      editor.getSession().setMode('ace/mode/css');
      editor.getSession().setTabSize(4); // 缩进 4 个字符
      editor.getSession().setUseSoftTabs(true); // 使用空格缩进
      editor.setFontSize(14);
      editor.setShowPrintMargin(false);

      // 设置自定义 CSS 内容
      editor.setValue(State.getConfig(key));
    });

    // 重置样式
    $$(document).on('click', '#setting .reset-custom-css', function() {
      let type = $$(this).data('type');

      mdui.confirm('该操作将清空你的自定义 CSS，并恢复为系统默认样式', '确认重置该样式？', function() {
        State.removeConfig(type);
        _this.editors[type].setValue(State.getConfig(type));
        Pubsub.emit('custom-css-changed');
      }, function(){}, {
        confirmText: '确认',
        cancelText: '取消',
        history: false
      });
    });

    // 重置所有自定义样式
    $$(document).on('click', '#setting .reset-all-custom-css', function() {
      mdui.confirm('该操作将清空你所有的自定义 CSS，并恢复为系统默认样式', '确认重置所有样式？', function() {
        _this.resetCustomCSS();

        mdui.snackbar({
          message: '已重置所有样式',
          position: 'left-bottom'
        });

      }, function(){}, {
        confirmText: '确认',
        cancelText: '取消',
        history: false
      });
    });

    // 保存样式
    $$(document).on('click', '#setting .save-custom-css', function() {
      let type = $$(this).data('type');

      State.setConfig(type, _this.editors[type].getValue());
      Pubsub.emit('custom-css-changed');
      mdui.snackbar({
        message: '已保存',
        position: 'left-bottom'
      });
    });

    // 切换主题时，同时切换编辑器主题
    Pubsub.subscribe('set-theme', (theme) => {
      $$.each(_this.editors, (key, editor) => {
        if (theme === 'light') {
          editor.setTheme('ace/theme/chrome');
        }

        if (theme === 'dark') {
          editor.setTheme('ace/theme/idle_fingers');
        }
      });
    });
  }

  /**
   * 重置所有自定义样式
   */
  resetCustomCSS() {
    const _this = this;

    State.removeConfig('markdownCSS');
    State.removeConfig('markdownLightCSS');
    State.removeConfig('highlightDarkCSS');
    State.removeConfig('highlightLightCSS');

    _this.editors.markdownCSS.setValue(State.getConfig('markdownCSS'));
    _this.editors.markdownLightCSS.setValue(State.getConfig('markdownLightCSS'));
    _this.editors.highlightDarkCSS.setValue(State.getConfig('highlightDarkCSS'));
    _this.editors.highlightLightCSS.setValue(State.getConfig('highlightLightCSS'));

    Pubsub.emit('custom-css-changed');
  }
}

export default PageSetting;